/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import core.exceptions.DBAccessException;
import core.objects.BaseObject;
import core.objects.BookLoan;
import core.objects.enums.LoanStatusEnum;
import db.DBAccessEngine;
import db.IDBAccess;
import db.threads.DBAccessThread;
import db.threads.IDBAccessThread;
import java.awt.Color;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 *
 * @author abadi
 */
public class JPanelLoanLine extends javax.swing.JPanel {

    private BookLoan loan;
    private boolean isLoanedFromMe;

    /**
     * Creates new form JPanelLoanLine
     */
    public JPanelLoanLine(BookLoan loan, boolean isLoanedFromMe) {
        this.loan = loan;
        this.isLoanedFromMe = isLoanedFromMe;
        initComponents();
        if (isLoanedFromMe) {
            jLabelUser.setText("Loaned To:");
        } else {
            jLabelUser.setText("Loaned From:");
        }
        initFields();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelBookName = new javax.swing.JLabel();
        jLabelUser = new javax.swing.JLabel();
        jLabelWhen = new javax.swing.JLabel();
        jLabelTerminate = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 255)));
        setOpaque(false);

        jLabelBookName.setText("Book Name:");

        jLabelUser.setText("User:");

        jLabelWhen.setText("When:");

        jLabelTerminate.setText("[Terminate]");
        jLabelTerminate.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
			public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabelTerminateMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelBookName, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(jLabelUser, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addComponent(jLabelWhen, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelTerminate, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelBookName)
                    .addComponent(jLabelUser)
                    .addComponent(jLabelWhen)
                    .addComponent(jLabelTerminate))
                .addGap(12, 12, 12))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jLabelTerminateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelTerminateMouseClicked
        if (!jLabelTerminate.isEnabled()) {
            return;
        }
        updateLoanStatus(loan, LoanStatusEnum.Finished);
        jLabelTerminate.setEnabled(false);
        jLabelTerminate.setForeground(Color.GRAY);
    }//GEN-LAST:event_jLabelTerminateMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabelBookName;
    private javax.swing.JLabel jLabelTerminate;
    private javax.swing.JLabel jLabelUser;
    private javax.swing.JLabel jLabelWhen;
    // End of variables declaration//GEN-END:variables

    private void initFields() {
        final int userId = (isLoanedFromMe ? loan.getLoanedTo() : loan.getLoanerId());
        final JPanelLoanLine thisObj = this;

        DBAccessThread.invoke(new IDBAccessThread() {

            @Override
            public Object onCreateQuery() throws DBAccessException {
                return DBAccessEngine.User().select(userId);
            }

            @SuppressWarnings("unchecked")
			@Override
            public void onAccessFinished(Object response) {
                List<BaseObject> userList = (List<BaseObject>) response;
                if (userList != null && userList.size() > 0) {
                    GUIUtils.initTextHeaderJlabel(jLabelUser, userList.get(0).getName());
                }
            }

            @Override
            public void onAccessFailed(DBAccessException e) {
                GUIUtils.showMessageError(e, thisObj);
            }
        });

        DBAccessThread.invoke(new IDBAccessThread() {

            @Override
            public Object onCreateQuery() throws DBAccessException {
                return DBAccessEngine.Book().select(loan.getBookId());
            }

            @SuppressWarnings("unchecked")
			@Override
            public void onAccessFinished(Object response) {
                List<BaseObject> userList = (List<BaseObject>) response;
                if (userList != null && userList.size() > 0) {
                    GUIUtils.initTextHeaderJlabel(jLabelBookName, userList.get(0).getName());
                }
            }

            @Override
            public void onAccessFailed(DBAccessException e) {
                     GUIUtils.showMessageError(e, thisObj);
            }
        });

        GUIUtils.initTextHeaderJlabel(jLabelWhen, GUIUtils.removeSecondsFromTimestamp(loan.getStartDate()));
        GUIUtils.setURLLink(jLabelTerminate, null, false);
        if (loan.getStatus() != LoanStatusEnum.Ongoing) {
            jLabelTerminate.setEnabled(false);
            setForeground(Color.GRAY);
        }
    }

    @SuppressWarnings("unchecked")
	public static void updateLoanStatus(BookLoan loan, LoanStatusEnum newLoanStatus) {
        try {
            if (newLoanStatus == LoanStatusEnum.Finished) {
                Timestamp now = new Timestamp(new Date().getTime());
                loan.setEndDate(now);
            }
            loan.setStatus(newLoanStatus);
            ((IDBAccess<BookLoan>) DBAccessEngine.BookLoan()).update(loan);
        } catch (DBAccessException ex) {
            GUIUtils.showMessageError(ex, null);
        }
    }
}
